/**
 * 
 */
package com.zx.mes.service.impl;

import com.zx.mes.service.RbacService;


import com.zx.mes.service.entity.User;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import javax.servlet.http.HttpServletRequest;
import java.util.Set;

/**
 * @author zhailiang
 *
 */
@Component("rbacService")
public class RbacServiceImpl implements RbacService {

	private Logger logger = LoggerFactory.getLogger(getClass());

	private AntPathMatcher antPathMatcher = new AntPathMatcher();

	@Override
	public boolean hasPermission(HttpServletRequest request, Authentication authentication) {
		Object principal = authentication.getPrincipal();

		boolean hasPermission = false;

		if (principal instanceof User) {

			logger.info("当前操作需要的权限:[{}]",request.getRequestURI());

			//如果用户名是admin，就永远返回true
			if (StringUtils.equals(((User) principal).getUsername(), "admin")) {
				hasPermission = true;
			} else {
				// 读取用户所拥有权限的所有URL
				Set<String> urls = ((User) principal).getUrls();
				for (String url : urls) {
//						logger.info(url + " : "+request.getRequestURI());
						if (StringUtils.isNotBlank(url) && antPathMatcher.match(url, request.getRequestURI())) {
							hasPermission = true;
							break;
						}
				}
			}
		}

		return hasPermission;
	}

}
